-- v0.01

apidir=shell.resolve("api")
tmpdir=shell.resolve("tmp")

-- For editing out of Minecraft I use an editor that needs an extension (.lua) to get syntax highlighting working
-- To save the ballache of copying and renaming it to a non-extensioned file, I just do that here in the script..
fs.delete(tmpdir.."/brum")
fs.delete(tmpdir.."/logger")
fs.copy(apidir.."/brum.lua",tmpdir.."/brum")
fs.copy(apidir.."/logger.lua",tmpdir.."/logger")

os.unloadAPI(tmpdir.."/brum")
os.loadAPI(tmpdir.."/brum")
os.unloadAPI(tmpdir.."/logger")
os.loadAPI(tmpdir.."/logger")

-- Some global flags to control turtle behaviour
local quitflag = false -- Used to break out of the main routine if there is an error
local completed = false -- Used to signal that the turtle has completed what was asked of it

-- How many inventory slots does the turtle have?
invSlots = 16

-- Refuel if turtle's remaining number of moves are lower than...
brum.setRefuelLevel(100)

-- For rednet message broadcasting to base logging console...
consoleID=1 -- Send messages back to console ID 1

local tArgs = { ... }
term.clear()
term.setCursorPos(1,1)
rednet.open("right") -- Open wireless modem on RH side for communication to base console


------------------
-- MAIN ROUTINE --
------------------

local width = 20
local length = 100
logger.setDebug()

if #tArgs > 0 then
  if tArgs[1] == "help" or tArgs[1] == "Help" then
    print("Usage: stepmine [width] [length]")
    print()
    print("For example, 'stepmine 40 100' would mine a channel 40 blocks")
    print("wide, 100 blocks 'in', from current height")
    print()
    print("If ommitted, [width] defaults to 20 and [length] to 100")
    quitflag = true
	elseif #tArgs == 2 then
		width=tonumber(tArgs[1])
		length=tonumber(tArgs[2])
	elseif #tArgs == 1 then
	  width=tonumber(tArgs[1])
  end
end

local refuelLevel = brum.getRefuelLevel()
local currentFuel = brum.fuelcheck()

if currentFuel==0 then
	-- We have no fuel in stock
	logger.crit("No initial fuel")
	error("No initial fuel")
elseif (currentFuel<refuelLevel) then
	logger.crit("Fuel level < "..refuelLevel.." - please provide more")
	error("Low initial fuel - please provide more")
end

print("w="..width..",l="..length)
logger.info("Stepmine - width "..width..", length "..length)

local currentDepth = 0 -- current level we're mining; start at 0, works DOWN!
local currentIn = 0 -- number of steps in (along Z axis) we've made
local hitRockBottom = false -- the level at which we can't go any deeper
local offsetX = 0
local offsetZ = 0

brum.setActive()

while (not hitRockBottom) and (currentIn<length) do
	local areaResult = false
	local errorReason = ""
	
	-- While we've not dug the whole square out, keep attempting it, unfilling at the surface as needed
	while not areaResult do

		brum.orientMe(0)

		if currentIn>0 then
			if not brum.moveZ(currentIn) then
				-- Must be bedrock sticking up, consider ourselves as deep as we can go
				hitRockBottom=true
			end
		end
		if currentDepth<0 then
			if not brum.moveY(currentDepth) then
				-- As deep as we can go
				hitRockBottom=true
			end
		end
		
		local cx,cy,cz = brum.getCurrentPos()
		local result, reason
		
		-- Dig this level's rectangle
		areaResult,errorReason,offsetX,offsetZ = brum.mineRectangle(offsetX,offsetZ,width,length-currentIn)
		if (not areaResult) or (string.len(errorReason)>0) then
			logger.info("Area not finished : ["..errorReason.."]")
			-- We didn't mine the whole square because of blockage, fuel or we're full... verify what to do...
			if (errorReason=="full" or errorReason=="fuel") then
				logger.info("Return home, dump load & refuel")
				result, reason = brum.returnXYZ(0,currentDepth,currentIn)
				result, reason = brum.moveY(0)
				result, reason = brum.returnXYZ(0,0,0)
			  brum.orientMe(2)
			  brum.dumpLoad()
		  	brum.getFuel()
			  logger.info("Resume at "..offsetX..","..offsetZ)	
			else
				--Must be blocked while processing the area - so abort the area
				logger.info("Abort this square")
				brum.returnXYZ(0,currentDepth,currentIn)
				areaResult=true -- to break out of while loop
			end	
		else
			logger.info("Square complete")
			brum.returnXYZ(0,currentDepth,currentIn)
			areaResult=true
	  end
	end -- while not areaResult

	if not hitRockBottom then
		currentDepth=currentDepth-1
	end
	
	if currentIn<length then
		currentIn=currentIn+1
	end
	
end

logger.info("Mine complete")
brum.returnXYZ(0,currentDepth,currentIn)
brum.moveY(0)
brum.returnXYZ(0,0,0)
-- Spit it out!
brum.orientMe(2)
brum.dumpLoad()
brum.orientMe(0)
brum.setFinished()

rednet.close("right")
